#!/usr/bin/env python3

import os
import sys

import common

class Main(common.TestCliFunction):
    def __init__(self):
        super().__init__(
            supported_archs=common.consts['crosstool_ng_supported_archs'],
        )
        self.add_argument(
            'tests',
            nargs='*',
            help='''\
If given, run only the given tests. Otherwise, run all tests.
'''
        )

    def timed_main(self):
        run = self.import_path_main('run')
        run_args = self.get_common_args()
        if self.env['emulator'] == 'gem5':
            run_args['userland_build_id'] = 'static'
        if self.env['tests'] == []:
            baremetal_source_exts = (self.env['c_ext'], self.env['asm_ext'])
            paths = []
            for f in os.listdir(self.env['baremetal_source_dir']):
                path = os.path.join(self.env['baremetal_source_dir'], f)
                if os.path.isfile(path) and os.path.splitext(path)[1] in baremetal_source_exts:
                    paths.append(path)
            for root, dirs, files in os.walk(self.env['baremetal_source_arch_dir'], topdown=True):
                dirs[:] = [d for d in dirs if d != 'interactive']
                for file in files:
                    path = os.path.join(root, file)
                    if os.path.splitext(path)[1] in baremetal_source_exts:
                        paths.append(path)
            sources = []
            for path in paths:
                if not (
                        self.env['emulator'] == 'gem5' and os.path.basename(path).startswith('semihost_') or
                        self.env['emulator'] == 'qemu' and os.path.basename(path).startswith('gem5_')
                    ):
                        sources.append(os.path.relpath(path, self.env['baremetal_source_dir']))
        else:
            sources = self.env['tests']
        for source in sources:
            run_args['baremetal'] = source
            run_args['ctrl_c_host'] = True
            if os.path.splitext(os.path.basename(source))[0] == 'multicore':
                run_args['cpus'] = 2
            self.run_test(run, run_args, source)

if __name__ == '__main__':
    Main().cli()
